package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.Result;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.InitVodObject;
import com.atguigu.vod.utils.VodPropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
public class VodController {
    @Autowired
    private VodService vodService;

    @PostMapping("uploadVideo")
    public Result uploadVideo(MultipartFile file){
        //返回的是阿里云视频的id，没有返回地址，因为地址没有加密，就可以直接获取视频，不建议使用
        //但是加密的视频地址获取了也没有如何意义，获取视频id来查询视频
        String videoId=vodService.uploadAliyunVideo(file);
        return Result.ok().data("videoId",videoId);
    }

    //删除阿里云中的视频
    @DeleteMapping("removeVideo/{videoId}")
    public Result removeVideo(@PathVariable String videoId){
        try {
            //初始化对象
            DefaultAcsClient client = InitVodObject.initVodClient(VodPropertiesUtil.ACCESS_KEY_ID, VodPropertiesUtil.ACCESS_KEY_SECRET);
            //初始化删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频的id值
            request.setVideoIds(videoId);
            //调用方法删除视频
            client.getAcsResponse(request);
            return Result.ok();
          }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"删除视频失败");
          }
    }

    //删除课程中同时删除多个视频
    @DeleteMapping("removeAllVideo")
    public Result removeAllVideo(@RequestParam("videoIdList") List<String> videoIdList){
        vodService.removeAllVideoList(videoIdList);
        return Result.ok();
    }

    //根据视频的videoSourceId获取到视频的播放凭证
    @GetMapping("gePlayAuth/{id}")
    public Result getPlayAuth(@PathVariable String id){
        try {
            //初始化客户端
            DefaultAcsClient client=InitVodObject.initVodClient(VodPropertiesUtil.ACCESS_KEY_ID,VodPropertiesUtil.ACCESS_KEY_SECRET);
            //创建获取凭证的request和response的对象
            GetVideoPlayAuthRequest request=new GetVideoPlayAuthRequest();
            //向request设置视频的id
            request.setVideoId(id);
            //获取到response中的数据
            GetVideoPlayAuthResponse response=client.getAcsResponse(request);
            //获取到视频的凭证
            String playAuth = response.getPlayAuth();
            return Result.ok().data("playAuth",playAuth);
        }catch (Exception e){
            throw new GuliException(20001,"获取视频凭证失败");
        }
    }
}
